//
//  WBComposeViewController.swift
//  simpleWeibo
//
//  Created by sunmumu on 2019/3/29.
//  Copyright © 2019 孙林. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var toolbar: UIToolbar!
    @IBOutlet var sendButton: UIButton!
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupNotification()
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.becomeFirstResponder()
    }
    
    // MARK: - Notification
    func setupNotification() {
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
    }
    
    @objc func keyboardChanged(n: Notification) {
        
        guard let rect = (n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duration = (n.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
            return
        }
        
        let offset = view.bounds.height - rect.origin.y
        if offset > 44 {
            toolbarBottomConstraint.constant = offset
        } else {
            toolbarBottomConstraint.constant = 44;
        }
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - Action
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
        
    }
    
    @IBAction func postStatus(_ sender: UIButton) {
        //1 获取微博文字
        guard let text = textView.text else {
            return
        }
        
        let image: UIImage? = UIImage(named: "refreshbg")
        //2 发布微博
        WBNetWorkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            print(result ?? [])
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: message)
            if isSuccess {
                SVProgressHUD.setDefaultStyle(.light)
                self.close()
                
            }
        }
    }
    
    @objc func emoticonKeyboard() {
        let inputView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 253))
        inputView.backgroundColor = UIColor.blue
        
        textView.inputView = (textView.inputView == nil) ? inputView : nil
        
        textView.reloadInputViews()
    }
    
}

// MARK: - UITextViewDelegate
extension WBComposeViewController : UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
    }
    
}

// MARK: - UI设置
extension WBComposeViewController {
    func setupUI() {
        view.backgroundColor = UIColor.white
        setupNav()
        setupToolbar()
        setupSubView()
        
    }
    
    func setupSubView() {
        
        var origin =  textView.frame.origin
        let top = UIApplication.shared.statusBarFrame.size.height
        origin.y = top + 44
        textView.frame.origin = origin
        textView.delegate = self
    }
    
    func setupToolbar() {
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            guard let imageName = s["imageName"] else {
                continue
            }
            let imageNameHL = imageName + "_highlighted"
            
            let btn = UIButton()
            btn.setImage(UIImage(named: imageName), for: .normal)
            btn.setImage(UIImage(named: imageNameHL), for: .highlighted)
            btn.sizeToFit()
            
            items.append(UIBarButtonItem(customView: btn))
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
            if s["actionName"] != nil {
                btn.addTarget(self, action: Selector(s["actionName"] ?? ""), for: .touchUpInside)
            } else {
                
            }
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.titleView = titleLabel
        sendButton.isEnabled = false
    }
    
}
